package com.example.note.model.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Home-pc
 */
@Slf4j
public class JwtUtils {
    //有效时间5分钟
    private static  final long expiration = 5 * 60 * 1000;
    //这是一个签名
    private static  final String secretString  = "qPPUoU2Chg8zVPJU3rO+ZOdazcgrvVxs6Su4U/izjHM=";
    //对签名进行编码
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    public static String genToken(Map<String,Object> claim){
        String token = Jwts.builder()
                .setClaims(claim)//设置载荷信息
                .setExpiration(new Date(System.currentTimeMillis() + expiration))//设置过期时间
                .signWith(key)//设置签名
                .compact();
        return token;
    }


    public static Claims parseToken(String token){
        if(token == null){
            return null;
        }
        //创建解析器，构建签名密钥
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        //拿着密钥解析令牌
        Claims claims = null;
        try{
            claims = build.parseClaimsJws(token).getBody();
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("解析token失败，token" + token);
            log.error("解析token失败，token" + claims.toString());
        }

        return claims;
    }

    public static Integer getUserIdFromToken(String token){
        Claims claims = parseToken(token);
        if(claims == null){
            return null;
        }
       return (Integer) claims.get("id");
    }

}
